<?php

defined('BASEPATH') or die('forbidden');

class Common_Model Extends Model {

    function _init() {
        //定义判断当前是否为主服务器
        header("Access-Control-Allow-Origin:*");
        //判断用户是否在IP白名单中
        if (!check_ip(get_ip(), $this->config['ip_whitelist'])) {
            exit;
        }
        //包含模块语言包
        global $lang;
        //自动加载的语言包
        $langarr = array('js', 'menu', 'common');
        $appname = trim(base_url(), '/');
        $langname = isset($this->config['languages'][$appname]) ? $this->config['languages'][$appname] : 'zh_CN';
        array_push($langarr, segment(0, 'index'));
        $langarr = array_unique($langarr);
        foreach ($langarr as $m => $n) {
            $filename = APPPATH . "languages/{$langname}/{$n}.php";
            if (is_file($filename)) {
                include $filename;
                //只有JS包和全局才输出到客户端
                if ($n == 'js') {
                    $this->view->assign("jslang", $lang);
                }
            }
        }
        $this->view->assign("langname", $langname);
        $this->view->assign("user_id", $this->input->get('user_id'));
        $this->view->assign("params", $_GET);
        $view = translate('VIEW');
        $add = translate('ADD');
        $edit = translate('EDIT');
        $del = translate('DEL');
        $item = array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del);
        //权限管理权限树列表
        $permissionarray = array(
            'general' => array(
                'name' => translate('MENU_GENERAL'),
                'item' => array(
                    'main' => array('name' => translate('HOME')),
                    'config' => array('name' => translate('MENU_GENERAL_CONFIG'), 'item' => array('index' => $view, 'edit' => $edit, 'restore' => translate('RESTORE')),),
                    'crontab' => array('name' => translate('MENU_GENERAL_CRONTAB'), 'item' => $item,),
                    'database' => array('name' => translate('MENU_GENERAL_DATABASE'), 'item' => array('index' => $view, 'browser' => translate('BROWSER'), 'repair' => translate('REPAIR'), 'execute' => translate('EXECUTE')),),
                    'logs' => array('name' => translate('MENU_GENERAL_LOGS')),
                    'language' => array('name' => translate('MENU_GENERAL_LANGUAGE'), 'item' => $item,),
                    'personal' => array('name' => translate('MENU_GENERAL_PERSONAL')),
                    'checkenv' => array('name' => translate('MENU_GENERAL_CHECKENV')),
                    'search' => array('name' => translate('MENU_GENERAL_SEARCH'), 'hide' => true),
                    'notice' => array('name' => translate('MENU_GENERAL_NOTICE'), 'item' => $item,),
                    'cache' => array('name' => translate('MENU_GENERAL_CACHE')),
                ),
                'append' => array(
                    array('text' => translate('LOGOUT'), 'url' => 'index/logout', 'nopermission' => true, 'target' => '_parent'),
                )
            ),
            'user' => array(
                'name' => translate('MENU_USER'),
                'item' => array(
                    'user' => array('name' => translate('MENU_USER_USER'), 'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del, 'basic' => translate('MENU_USER_USER_BASIC'), 'medium' => translate('MENU_USER_USER_MEDIUM'), 'advance' => translate('MENU_USER_USER_ADVANCE'),),),
                    'order' => array('name' => translate('MENU_USER_ORDER'), 'item' => $item,),
                )
            ),
            'diary' => array(
                'name' => translate('MENU_DIARY'),
                'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del,)
            ),
            'budget' => array(
                'name' => translate('MENU_BUDGET'),
                'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del,)
            ),
            'category' => array(
                'name' => translate('MENU_CATEGORY'),
                'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del,)
            ),
            'note' => array(
                'name' => translate('MENU_NOTE'),
                'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del,)
            ),
            'account' => array(
                'name' => translate('MENU_ACCOUNT'),
                'item' => array('index' => $view, 'add' => $add, 'edit' => $edit, 'del' => $del,)
            ),
            'bill' => array(
                'name' => translate('MENU_BILL'),
                'item' => array(
                    'bill' => array('name' => translate('MENU_USER_ORDER'), 'item' => $item,),
                )
            ),
            'bbs' => array(
                'name' => translate('MENU_BBS'),
                'item' => array(
                    'thread' => array('name' => translate('MENU_USER_ORDER'), 'item' => $item,),
                    'reply' => array('name' => translate('MENU_USER_HERO'), 'item' => $item,)
                )
            ),
            'role' => array(
                'name' => translate('MENU_ROLE'),
                'item' => array(
                    'role' => array('name' => translate('MENU_ROLE_ROLE'), 'item' => $item),
                    'admin' => array('name' => translate('MENU_ROLE_ADMIN'), 'item' => $item),
                    'log' => array('name' => translate('MENU_ROLE_LOG'), 'item' => $item),
                ),
            ),
        );
        $this->view->assign("permission", $permissionarray);

        //左侧导航菜单列表数组生成
        $menuarray = array();
        foreach ($permissionarray as $m => $n) {
            $menuarray[$m] = $this->get_permission_item($m, $permissionarray, isset($n['append']) ? $n['append'] : array());
        }
        $this->view->assign("menu", $menuarray);
        //自动匹配标题
        $na = 'MENU' . str_replace('_INDEX', '', str_replace('/', '_', strtoupper(get_instance()->path_info)));
        if (isset($lang[$na])) {
            $this->view->assign("title", $lang[$na]);
        }
        $this->online();
    }

    function online() {
        $adminname = $this->auth->username;
        $filename = DATAPATH . 'chats/online.php';
        if (!file_exists($filename))
            file_put_contents($filename, '<?php exit;?>');
        $content = str_replace('<?php exit;?>', '', file_get_contents($filename));
        $onlines = json_decode($content, true);
        $result = $data = array();
        $isexist = false;
        $urls = parse_url($this->input->server('HTTP_REFERER'));
        $url = is_array($urls) && $urls['path'] != '' ? $urls['path'] : '';
        if (is_array($onlines)) {
            foreach ($onlines as $key => $value) {
                $value = (array) $value;
                if ($adminname != '' && $value['nickname'] == $adminname) {
                    $isexist = true;
                    $value['last_activity'] = date('Y-m-d H:i:s');
                    $value['url'] = $url;
                }
                if (strtotime($value['last_activity']) > (time() - 600))
                    $result[] = $value;
            }
        }
        if ($adminname != '' && !$isexist)
            $result[] = array('nickname' => $adminname, 'last_activity' => date('Y-m-d H:i:s'), 'url' => $url);

        $fp = fopen($filename, "w+");
        if (@flock($fp, LOCK_EX)) {
            @fputs($fp, '<?php exit;?>' . json_encode($result));
            @flock($fp, LOCK_UN);
        }
        @fclose($fp);

        //统计在线
        $online_cur_t = $online_list_t = array();
        foreach ($result as $key => $value) {
            $online_list_t[] = "<li><i>{$value['nickname']}</i><span>{$value['last_activity']}</span></li>";
            if ($url == $value['url'])
                $online_cur_t[] = "<a href='javascript:;' title=''>{$value['nickname']}</a>";
        }
        $data['online_total'] = count($result);
        $data['online_cur'] = implode('|', $online_cur_t);
        $data['online_list'] = implode('', $online_list_t);
        $data['online_cur_total'] = count($online_cur_t);
        $this->view->assign($data);
    }

    function get_permission_item($module, $data, $append = array()) {
        if (isset($data[$module])) {
            $item = array();
            $editarray = array('add', 'edit', 'del');
            foreach ($data[$module]['item'] as $m => $n) {
                if (in_array($m, $editarray) || (isset($n['hide']) && $n['hide']))
                    continue;
                if ($m == 'index') {
                    $n['name'] = $data[$module]['name'];
                }
                $one = array('text' => $n['name'], 'url' => "{$module}/{$m}");
                if (isset($n['target'])) {
                    $one['target'] = $n['target'];
                }
                $item[] = $one;
            }
            $data[$module]['item'] = array_merge($item, $append);
            return $data[$module];
        } else {
            return array();
        }
    }

    function get_flexigrid_params() {
        $sortname = $this->input->post("sortname");
        $sortorder = $this->input->post("sortorder");
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");
        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");
        $qop = $this->input->post("qop", "strtolower");
        $colkey = $this->input->post("colkey");
        $colsarr = explode(',', $this->input->post("colsinfo"));
        $field = array();
        //给字段加上``符号
        foreach ($colsarr as $m => $n) {
            $pos = stripos($n, ".");
            $field[] = $pos !== false ? substr($n, 0, $pos + 1) . "`" . substr($n, $pos + 1) . "`" : "`{$n}`";
        }
        $colsinfo = implode(",", $field);
        $searchitems = isset($_POST['searchitems']) ? $_POST['searchitems'] : array();
        //严格模式则加上： && in_array($qtype, explode(',', $colsinfo))
        if ($qtype && $qop && $query != '') {
            $query = $query == 'null' ? '' : $query;
            $mark = $qop == 'like' ? '%' : '';
            $pos = stripos($qtype, ".");
            $qtype = $pos !== false ? substr($qtype, 0, $pos + 1) . "`" . substr($qtype, $pos + 1) . "`" : "`{$qtype}`";
            $where[] = "{$qtype} {$qop} '{$mark}{$query}{$mark}'";
        } else {
            $where[] = '1=1';
        }
        foreach ($searchitems as $m => $n) {
            $sarray = explode('$$', $n);
            if (!isset($sarray[0]))
                continue;
            $field = $sarray[0];
            $pos = stripos($field, ".");
            $sval = isset($sarray[2]) ? $sarray[2] : '';
            $sval = $sval == 'null' ? '' : $sval;
            $sop = isset($sarray[1]) ? $sarray[1] : '=';
            $mark = strtolower($sop) == 'like' ? '%' : '';
            $sfield = $pos !== false ? substr($field, 0, $pos + 1) . "`" . substr($field, $pos + 1) . "`" : "`{$field}`";
            $where[] = "{$sfield} {$sop} '{$mark}{$sval}{$mark}'";
        }
        $where = implode(" AND ", $where);
        $page = $page ? intval($page) : 1;
        $offset = ($page - 1) * $rp;
        if (!$rp || !$page || !$colsinfo || !$colkey)
            error(translate('C_INVALID_PARAMS'));
        return array($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page);
    }

}